################################################################################
# File: manageWS.py
# Package: itacqos.uddi.views
# Author: Vincent Pretre
# Last update: $LastChangedDate: 2009-02-28 16:25:51 +0000 (Sat, 28 Feb 2009) $
################################################################################

## @package itacqos.uddi.views.manageWS
#
# Those views allow creation, edition and deletion of web services

from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

from uddi.models import Category, Keyword, WebService, Vendor
from uddi.forms import RegisterForm, UpdateUserForm, VendorForm, ServiceForm

from common import cleanKW, newRender, getUser, createWSFolder, saveWSDL, saveModel, updateKW

import os
import urllib

## View used when creating a new service
def newService(request):
	template = ''
	dict = {'newService' : True}

	usr = getUser(request)
	if usr['isAuthenticated']:
		if usr['isVendor']:
			template = 'newService.html'
			if request.method == 'POST':
				form = ServiceForm(request.POST, request.FILES)
				
				if form.is_valid():
					form.cleaned_data['producedBy'] = usr['vendor']
					form.cleaned_data['percentageOfSuccessfulTests'] = 0
					form.cleaned_data['dir'] = ""
					ws = form.save()
		
					# Creates a directory for files linked to the service (wsdl, model, tests ...) and stores WSDL file and model
					createWSFolder(ws)
					saveWSDL(ws)
					saveModel(request, ws)

					# Stores keywords, this operation also save the ws
					updateKW(ws, form.cleaned_data['kw'])
					
					# If everything worked, user is sent back to the list of services
					dict['isVendor'] = usr['isVendor']
					dict['services'] = usr['vendor'].webservice_set.all()
					template = 'controlPanelWS.html'
				else:
					dict['form'] = form
			else:
				dict['form'] = ServiceForm()

		else:
			dict['errorMsg'] = 'Only vendors can access this page'
			dict['showLoginForm'] = True
			template = 'error.html'			
	else:
		dict['errorMsg'] = 'You must be authenticated to see this page'
		dict['showLoginForm'] = True
		template = 'error.html'
	
	return newRender(template, dict, request)


## This view is used to update a web service informations
# @param serviceId Identifier of the web service to delete
# @bug When editing a web service, its keywords do not appear in the form.
def editService(request, serviceId):
	template = ''
	dict = {'newService' : False, 'serviceId' : serviceId}
	
	usr = getUser(request)
	if usr['isAuthenticated']:
		if usr['isVendor']:
			template = 'newService.html'
			ws = get_object_or_404(WebService, pk = serviceId)
			
			if ws.producedBy == usr['vendor']:
			
				if request.method == 'POST':
					form = ServiceForm(request.POST, request.FILES, instance = ws)
					
					if form.is_valid():
						form.cleaned_data['producedBy'] = usr['vendor']
						ws = form.save()
			
						# Saves the new version of the model and WSDL file
						saveWSDL(ws, True)
						saveModel(request, ws, True)
	
						# Updates keywords
						updateKW(ws, form.cleaned_data['kw'])
						
						# If everything worked, user is sent back to the list of services
						dict['isVendor'] = usr['isVendor']
						dict['services'] = usr['vendor'].webservice_set.all()
						template = 'controlPanelWS.html'
					else:
						dict['form'] = form
				else:
					# Translates keywords list in text, separated by comma
					keywords  = ''
					for kw in ws.keywords.all():
						keywords = keywords + kw.name + ', '
					
					form = ServiceForm(instance = ws)
										
					dict['keywords'] = keywords
					dict['form'] = form

			else:
				dict['errorMsg'] = 'You can not update this web service'
				dict['showLoginForm'] = True
				template = 'error.html'				

		else:
			dict['errorMsg'] = 'Only vendors can access this page'
			dict['showLoginForm'] = True
			template = 'error.html'			
	else:
		dict['errorMsg'] = 'You must be authenticated to see this page'
		dict['showLoginForm'] = True
		template = 'error.html'	
	
	return newRender(template, dict, request)

## Changes status of a ws to public
# @param serviceId Identifier of the web service to delete
#
# Fake-function, all treatment is done by updateWSStatus()
def showService(request, serviceId):
	return updateWSStatus(request, serviceId, True)

## Changes status of a ws to hidden
# @param serviceId Identifier of the web service to delete
#
# Fake-function, all treatment is done by updateWSStatus()
def hideService(request, serviceId):
	return updateWSStatus(request, serviceId, False)

## Changes status of a ws.
# @param serviceId  Identifier of the service to update
# @param status Boolean, new status of the service (True -> public, False -> Hidden)
def updateWSStatus(request, serviceId, status):
	template = ''
	dict = {}
	
	usr = getUser(request)
	
	if usr['isAuthenticated']:
		if usr['isVendor']:
			ws = get_object_or_404(WebService, pk=serviceId)
			if ws.producedBy == usr['vendor']:
				ws.public = status
				ws.save()
				
				# If everything worked, user is sent back to the list of services
				dict['isVendor'] = usr['isVendor']
				dict['services'] = usr['vendor'].webservice_set.all()
				template = 'controlPanelWS.html'
			else:
				dict['errorMsg'] = 'You can not update status of this web service'
				dict['showLoginForm'] = True
				template = 'error.html'
		else:
			dict['errorMsg'] = 'Only vendors can access this page'
			dict['showLoginForm'] = True
			template = 'error.html'			
	else:
		dict['errorMsg'] = 'You must be authenticated to see this page'
		dict['showLoginForm'] = True
		template = 'error.html'
		
	return newRender(template, dict, request)

## View used when deleting a web service
# @param serviceId Identifier of the web service to delete
def deleteService(request, serviceId):
	template = ''
	dict = {}

	usr = getUser(request)
	if usr['isAuthenticated']:
		if usr['isVendor']:
			ws = get_object_or_404(WebService, pk=serviceId)
			if ws.producedBy == usr['vendor']:
				if request.GET.has_key('valid') and request.GET['valid'] == 'True':
					ws.delete()
					dict['isVendor'] = usr['isVendor']
					dict['services'] = usr['vendor'].webservice_set.all()
					template = 'controlPanelWS.html'
				else:
					dict['status'] = False
					template = 'deleteService.html'
			else:
				dict['errorMsg'] = 'You can not delete this web service'
				dict['showLoginForm'] = True
				template = 'error.html'
		else:
			dict['errorMsg'] = 'Only vendors can access this page'
			dict['showLoginForm'] = True
			template = 'error.html'			
	else:
		dict['errorMsg'] = 'You must be authenticated to see this page'
		dict['showLoginForm'] = True
		template = 'error.html'
		
	return newRender(template, dict, request)	
